package com.project.genesis.oss.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.genesis.base.BaseEntity;
import com.project.genesis.common.util.UUIDUtil;
import com.project.genesis.entity.oss.FileInfo;
import com.project.genesis.oss.config.MedioHttpRequestHandler;
import com.project.genesis.oss.mapper.FileInfoMapper;
import com.project.genesis.oss.service.FileInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * <p>
 * 文件信息表 服务实现类
 * </p>
 *
 * @author qtx
 * @since 2022-09-26
 */
@Service
public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> implements FileInfoService {
    @Value("${local-file}")
    private String filePath;
    @Value("${host-ip}")
    private String hostIp;
    @Autowired
    private MedioHttpRequestHandler medioHttpRequestHandler;

    @Override
    public FileInfo upload(MultipartFile file, HttpServletRequest request) {
        FileInfo info = new FileInfo();
        String realPath = filePath;
        //request.getSession().getServletContext().getRealPath("/uploadFile/");
        File dir = new File(realPath);
        if (!dir.isDirectory()) {
            dir.mkdirs();
        }
        try {
            String filename = file.getOriginalFilename();
            //服务端保存的文件对象
            assert filename != null;
            info.setName(filename);
            String[] split = filename.split("\\.");
            String newName = UUIDUtil.uuid() + "." + split[split.length - 1];
            info.setNewName(newName);
            File fileServer = new File(dir, newName);
            info.setPath(fileServer.getAbsolutePath());
            //实现上传
            file.transferTo(fileServer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return info;
    }

    @Override
    public String saveNew(MultipartFile file, HttpServletRequest request, String uuid, String otherId) throws UnknownHostException {
        boolean m = checkFileSize(file.getSize(), 20, "M");
        if (!m) {
            return "false";
        }
        FileInfo videoInfo = upload(file, request);
        videoInfo.setOtherId(otherId);
        videoInfo.setUuid(uuid);
        if (save(videoInfo)) {
            //获取request 设置IP地址
            if (StringUtils.isBlank(hostIp)){
                hostIp =  InetAddress.getLocalHost().getHostAddress();
            }
            return hostIp + ":8090" + "/oss/file/" + videoInfo.getNewName();
        }
        return "false";
    }

    @Override
    public void getPlay(String uuid, HttpServletRequest request, HttpServletResponse response) throws IOException,
            ServletException {
        FileInfo byId = getOne(Wrappers.lambdaUpdate(FileInfo.class).eq(FileInfo::getUuid, uuid));
        Path path = Paths.get(byId.getPath());
        if (Files.exists(path)) {
            String mimeType = Files.probeContentType(path);
            if (!StringUtils.isEmpty(mimeType)) {
                response.setContentType(mimeType);
            }
            request.setAttribute(MedioHttpRequestHandler.ATTR_FILE, path);
            medioHttpRequestHandler.handleRequest(request, response);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        }
    }

    @Override
    public void removeByOtherId(String otherId) {
        List<FileInfo> list = list(Wrappers.lambdaQuery(FileInfo.class)
                .eq(BaseEntity::getIsDelete, "0")
                .eq(FileInfo::getOtherId, otherId));
        list.forEach(e -> new File(e.getPath()).delete());
        remove(Wrappers.lambdaUpdate(FileInfo.class)
                .eq(BaseEntity::getIsDelete, "0")
                .eq(FileInfo::getOtherId, otherId));
    }

    /**
     * 判断文件大小
     *
     * @param len  文件长度
     * @param size 限制大小
     * @param unit 限制单位（B,K,M,G）
     * @return
     */
    public static boolean checkFileSize(Long len, int size, String unit) {
//        long len = file.length();
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }
}
